package cl.utalca.DB;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;



public class DataSourceManager {
	
	static protected String jndiName;
	
	public static Connection getConnection(){
		
		Connection conn = null;
		
		try{
			
			String path = "/cl/utalca/DB/database.properties";
			InputStream in = DataSourceManager.class.getResourceAsStream(path);
			
			Context initContext = new InitialContext();
			Properties props = new Properties();    
			props.load(in);
			jndiName = props.getProperty("JNDI_NAME");
			DataSource ds = (DataSource) initContext.lookup(jndiName);
			
			conn = ds.getConnection();
			conn.setAutoCommit(false);
			
			return conn;
		}
		catch( NamingException nex){
			
			nex.printStackTrace();
			return null;
		}
		catch (Exception ex){
			
			ex.printStackTrace();
			return null;
		}
	}
	
	static public void close(Statement stmt, ResultSet rs) throws SQLException{
		if (rs    != null) try { rs.close();    } catch (SQLException e) {throw e;}         
		if (stmt != null) try { stmt.close(); } catch (SQLException e) {throw e;}
	}
	
	static public void close(ResultSet rs, Statement stmt) throws SQLException{
		close(stmt,rs);
	}
	
	static public boolean closeOnSuccess(Connection connection){
		boolean ret = commit(connection);
		ret = close(connection) && ret;
		return ret;
	}
	
	static public boolean closeOnError(Connection connection){
		boolean ret = rollback(connection);
		ret = close(connection) && ret;
		return ret;
	}
	
	static public boolean close(Connection connection, boolean success){
		if(success){
			return closeOnSuccess(connection);
		}else{
			return closeOnError(connection);
		}		
	}
	
	
	static protected boolean setAutoCommit(Connection connection, Boolean autoCommit){
		try {
			connection.setAutoCommit(autoCommit);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	static protected boolean commit(Connection connection){
		try {
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	static protected boolean rollback(Connection connection){
		try {
			connection.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
		
	static protected boolean close(Connection connection){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}		
		return true;
	}
}
